<template>
<div class="cart-total">
    <h2>总计</h2>
    <p v-if="total >0">总金额：{{ total }} 元</p>
    <p v-else>购物车为空</p>
</div>
</template>

<script setup>
import {computed} from 'vue'

//定义接收的props，包括购物车商品数组
const props = defineProps(['items']);

//计算总金额
const total = computed(() => {
    //初始化总金额为0
    let totalAmount = 0;
    //遍历每个商品
    props.items.forEach(item => {
        //计算当前商品的总价
        const itemTotal = item.price * item.quantity;
        //当前商品总价累加到总金额中
        totalAmount = totalAmount + itemTotal
    })
    return totalAmount;
})

</script>

<style scoped>
.cart-total{
    font-weight: bold;
}
</style>